package com.sq.util.web;

import java.util.Map;

import org.apache.commons.codec.CharEncoding;
import org.apache.http.client.methods.HttpGet;

/**
 * @author sq
 *
 */
public class HttpGetUtil extends BaseHttpUtil {

    public static String execute(String url) throws Exception {
        return execute(new HttpGet(url), null, CharEncoding.UTF_8);
    }

    public static String execute(String baseUrl, Map<String, String> params) throws Exception {
        HttpGet httpGet = new HttpGet(genUrl(baseUrl, params));
        return execute(httpGet, null, CharEncoding.UTF_8);
    }

    public static String execute(String baseUrl, Map<String, String> headers, Map<String, String> params,
            String charset) throws Exception {
        HttpGet httpGet = new HttpGet(genUrl(baseUrl, params));
        return execute(httpGet, headers, charset);
    }

    public static String execute(String url, Map<String, String> headers, String charset) throws Exception {
        return execute(new HttpGet(url), headers, charset);
    }

    /**
     * get请求
     */
    private static String execute(HttpGet httpGet, Map<String, String> headers, String charset) throws Exception {
        setHeaders(httpGet, headers);
        return request(httpGet, charset);
    }

    private static String genUrl(String baseUrl, Map<String, String> params) {
        if (params == null) {
            return baseUrl;
        }
        if (params.isEmpty()) {
            return baseUrl;
        }
        StringBuilder urlSb = new StringBuilder(128);
        urlSb.append(baseUrl).append('?');
        StringBuilder paramSb = new StringBuilder(128);
        for (Map.Entry<String, String> entry : params.entrySet()) {
            paramSb.append('&').append(NetUtil.encode(entry.getKey()));
            paramSb.append('=').append(NetUtil.encode(entry.getValue()));
        }
        for (int i = 1, len = paramSb.length(); i < len; i++) {
            urlSb.append(paramSb.charAt(i));
        }
        String url = urlSb.toString();
        return url;
    }

}
